package com.gbase8c.dmt.db.oracle;

import com.gbase8c.dmt.db.object.ViewObject;
import com.gbase8c.dmt.model.migration.dto.DataSourceDto;
import com.gbase8c.dmt.model.migration.dto.TableDto;
import com.gbase8c.dmt.model.migration.dto.ViewDto;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ViewObjectImpl extends MetaImpl implements ViewObject {

    public ViewObjectImpl(DataSourceDto dataSourceDto) {
        super(dataSourceDto);
    }

    @Override
    public List<String> getNames(Map<String, Object> params) {
        String schema = (String) params.get("schema");
        String sql = "select view_name from all_views where owner = ?";
        List<String> viewNames = query(sql, new ColumnListHandler<String>(), schema);
        return viewNames;
    }

    @Override
    public ViewDto get(String name, Map<String, Object> params) {
        String schema = (String) params.get("schema");
        String sql = "select owner as schema, view_name as name,text as src_definition from all_views where owner = ? and view_name = ?";
        String columnListSql ="select owner as schema, table_name as \"table\", column_name as name, data_type, data_length, data_precision, data_scale nullable from all_tab_columns where owner = ? and table_name = ?";
        List<TableDto.ColumnDto> columnDtos = null;
        ViewDto viewDto = ViewDto.builder().build();
        Map<String,Object> viewMap = query(sql,new MapHandler(), schema, name);
        Map <String,Object> viewDtoMap = new HashMap<>();
        //将查询出来的结果map做驼峰转换
        viewMap.forEach((k,v) -> viewDtoMap.put(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,k.toLowerCase()),v));
        try {
            BeanUtils.populate(viewDto,viewDtoMap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        columnDtos = query(columnListSql,new BeanListHandler<>(TableDto.ColumnDto.class, new BasicRowProcessor(new GenerousBeanProcessor())), schema, name);
            viewDto.setColumnDtos(columnDtos);
            viewDto.setDs(dataSourceDto.getId());
        return viewDto;
    }

    @Override
    public ViewDto convert(ViewDto viewDto, Map<String, Object> params) {
        return null;
    }

    @Override
    public String sql(ViewDto viewDto, Map<String, Object> params) {
        return null;
    }
}
